package com.source.quartz.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import jdk.nashorn.internal.ir.CatchNode;

import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author wengqy
 * @Date 2020/12/16
 */
public class ThreadExcutorsDemo {
    public static void main(String[] args) {
      //  ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor()
    //    ExecutorService executorService = Executors.newFixedThreadPool(10);
       /* ExecutorService executorService = Executors.newSingleThreadExecutor();
         ExecutorService executorService = Executors.newCachedThreadPool();
        try {
            for (int i = 1; i <=1000 ; i++) {
                executorService.execute(myRunnable);
            }

        }catch (Exception e){

        }finally {
            executorService.shutdown();
        } */

        MyRunnable myRunnable = new MyRunnable();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                5,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
                );

        try{

            for (int i = 1; i <=13 ; i++) {
                TimeUnit.MILLISECONDS.sleep(100);

                threadPoolExecutor.execute(myRunnable);

            }
        }catch (Exception ee){

        }finally {
            threadPoolExecutor.shutdown();
        }



    }


}

class MyRunnable implements  Runnable{
 private       int  count = 15;

Object  obj = new Object();
    @Override
    public  void run() {
        while (true){

                synchronized (obj){
                    if(count>0){
                        try {
                            TimeUnit.MILLISECONDS.sleep(1000);
                            decrement();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else {
                        break;
                    }
                }



        }
    }

    private     void   decrement() {

   //  synchronized (MyRunnable.class){
         System.out.println(Thread.currentThread().getName()+"-------::::"+count);
         count=count-1;
 //    }

      /*  ReentrantLock reentrantLock = new ReentrantLock();
       try {
           reentrantLock.lock();

       }finally {
           reentrantLock.unlock();
       }*/
     //

    }
}
